package com.xu.sms.view;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.Header;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class MyImageView extends ImageView {

	private Context context;
	
	public MyImageView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		this.context = context;
	}

	public MyImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
	}

	public MyImageView(Context context) {
		super(context);
		this.context = context;
	}
	
	public Handler handler = new Handler(){
		
		public void handleMessage(Message msg) {
			//主线程更新ui
			Bitmap bm = (Bitmap) msg.obj;
			MyImageView.this.setImageBitmap(bm);
		}
	};

	public void setImageURI(String url_str) {
		
		AsyncHttpClient async = new AsyncHttpClient();
		async.get(url_str, new MyAsyncHttpResponseHandler());
		//new MyThread(url_str).start();
	}
	
	class MyAsyncHttpResponseHandler extends AsyncHttpResponseHandler{

		@Override
		public void onFailure(int statusCode, Header[] headers, byte[] responseBody,
				Throwable error) {
			Toast.makeText(context, "对不起服务端大哥可能去忙了", Toast.LENGTH_SHORT).show();
		}
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
			if(statusCode == 200){
				ByteArrayInputStream bais = new ByteArrayInputStream(responseBody);
				Bitmap bitMap = BitmapFactory.decodeStream(bais);
				Message msg = Message.obtain();
				msg.obj = bitMap;
				handler.sendMessage(msg);
			}
		}
	} 
	
	/*class MyThread extends Thread{
		public String url_str;
		public MyThread(String url_str){
			this.url_str = url_str;
		}
		
		@Override
		public void run() {
			
			 * 子线程请求资源
			 * 父线程更新UI
			 * 使用url来请求端的资源
			 
			try {
				URL url = new URL(url_str);
				HttpURLConnection con = (HttpURLConnection) url.openConnection();
				con.setRequestMethod("GET");
				con.setReadTimeout(10*1000);//设置请求的超时时间
				int code = con.getResponseCode();
				if(code == 200){
					InputStream in = con.getInputStream();
					Bitmap bm = BitmapFactory.decodeStream(in);
					Message msg = Message.obtain();
					msg.obj = bm;
					handler.sendMessage(msg);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}*/
	
	

}
